﻿using System;
using System.Drawing;
using System.Web;
namespace TCHSHue.BLL
{
    public class CaptchaBLL
    {
        float fontSize = 16;
        string pathBackGroundImage = "~/Style/Images/captcha1.png";

        public CaptchaBLL()
        {
            CharacterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
            CaptchaLength = 10;
        }

        public string CreateCaptchaText()
        {
            return GetRandomText();
        }

        private string GetRandomText()
        {
            char[] letters = CharacterSet.ToCharArray();
            string text = string.Empty;
            Random r = new Random();
            int num = -1;

            for (int i = 0; i < this.CaptchaLength; i++)
            {
                num = (int)(r.NextDouble() * (letters.Length - 1));
                text += letters[num].ToString();
            }
            return text;
        }

        public int CaptchaLength
        {
            get;
            set;
        }

        public string CharacterSet
        {
            get;
            set;
        }

        public Bitmap CreateCatchaImage(string text)
        {
            int imageWidth = Convert.ToInt32(((fontSize + 8) * text.Length));
            int imageHeight = Convert.ToInt32(fontSize * 2.5);

            Bitmap bmp = new Bitmap(imageWidth, imageHeight);
            var Grph = Graphics.FromImage(bmp);
            Grph.FillRectangle(new SolidBrush(Color.Lavender), 0, 0, bmp.Width, bmp.Height);

            var grp = Graphics.FromImage(bmp);
            Image background = Image.FromFile(HttpContext.Current.Server.MapPath(pathBackGroundImage));
            grp.DrawImage(background, new Rectangle(0, 0, bmp.Width, bmp.Height));

            Grph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            Grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            int xPos = 10;

            Font f = new Font("Arial", fontSize);

            char[] textArray = text.ToCharArray();
            int yPosition = 0;
            Random r = new Random();

            for (int i = 0; i < textArray.Length; i++)
            {
                if (i % 2 == 0)
                    Grph.RotateTransform(5);
                else
                    Grph.RotateTransform(-5);

                yPosition = (int)(r.NextDouble() * 10);

                Grph.DrawString(textArray[i].ToString(), f, new SolidBrush(Color.FromName("Black")), xPos, yPosition);
                xPos += 20;

            }
            return bmp;
        }

        private int yPos()
        {
            Random r = new Random();
            return (int)(r.NextDouble() * 10);
        }
    }
}